//
//  XMLParseHelper.swift
//  WineComing
//
//  Created by xiaozhi on 15/7/28.
//  Copyright (c) 2015年 xiaozhi. All rights reserved.
//

import UIKit

class XMLParseHelper: NSObject,NSXMLParserDelegate {
    var matchElement:String?
    var result:NSMutableString!
    var xmlParse:NSXMLParser!
    var found:Bool = false
    var compeledHanlde:((AnyObject?)->Void)?
    override init() {
        result = NSMutableString()
        super.init()
    }
    convenience init(data:NSData,matchElement:String,compeleteHandle:((AnyObject?)->Void)?){
        self.init()
//        println("create parser")
        xmlParse = NSXMLParser(data: data)
        self.matchElement = matchElement
        self.compeledHanlde = compeleteHandle
        xmlParse.delegate = self
        
        if !xmlParse.parse(){
//            println(xmlParse.parserError)
        }
    }
    deinit{
        print("helper deinit!")
    }
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]){
//         println("begin parser")
        if elementName==matchElement{
            found = true
//            println("find parser")
        }
    }
    func parser(parser: NSXMLParser, foundCharacters string: String?){
        if found{
            if let str = string{
                result.appendString(str)
            }
        }
    }
    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){
        if elementName==matchElement{
//            println("end parser")
            parser.abortParsing()
            let responsObj:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(result.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.AllowFragments)
            compeledHanlde?(responsObj)
            
        }
    }
    func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError){
//        compeledHanlde?(nil)
    }
}
